package com.phei.netty.chat3;

import java.net.InetSocketAddress;

import com.phei.netty.chat2.ChartServerInitializer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

public class ChatServer {
	
	private ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	private EventLoopGroup group = new NioEventLoopGroup();
	private Channel		 channel;
	public ChannelFuture start(InetSocketAddress address) {
		ServerBootstrap bootstrap =  new ServerBootstrap();
		bootstrap.group(group)
		.channel(NioServerSocketChannel.class)
		.childHandler(createInitializer(channelGroup));
		ChannelFuture future = bootstrap.bind(address);
		future.syncUninterruptibly();
		channel = future.channel();
		return future;
	}
	
	public ChannelInitializer<Channel> createInitializer(ChannelGroup group){
		return new ChatServerInitalizer(group);
	}
	
	public void destroy() {
		if(channel != null) {
			channel.close();
		}
		
		channelGroup.close();
		group.shutdownGracefully();
	}
	
	public static void main(String[] args) {
		ChatServer endpoint = new ChatServer();
		ChannelFuture future =  endpoint.start(new InetSocketAddress(8989));
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				endpoint.destroy();
			}
		});
		
		future.channel().closeFuture().syncUninterruptibly();
		
	}
	
}
